<?php

/**
 * Menashop
 *
 * LICENSE
 *
 * This source file is subject to the license that is bundled
 * with this project in the file LICENSE.txt
 *
 * @category   Menashop
 * @package    Menashop_Content
 * @subpackage Importer
 * @copyright  Copyright (c) 2011 Menashop UA Inc. (http://www.menashop.com.ua)
 * @license    LICENSE.txt
 * @version    1.0.0
 * @since      File available since Release 1.0.0
 */

/**
 * The importer for content XML
 * 
 * @category   Menashop
 * @package    Menashop_Content
 * @subpackage Importer
 * @copyright  Copyright (c) 2011 Menashop UA Inc. (http://www.menashop.com.ua)
 * @license    LICENSE.txt
 */
class Menashop_Content_Importer
{

    /**
     * The downloader for an import
     * @var Menashop_Downloader 
     */
    protected $_downloader = null;

    /**
     * The logger for an import
     * @var Zend_Log 
     */
    protected $_logger = null;

    /**
     * The configuration of an import
     * @var Zend_Config 
     */
    protected $_config = null;

    /**
     * Initialize the importer for content
     */
    public function __construct()
    {
        $this->_downloader = new Menashop_Downloader();
        $this->_logger = Zend_Registry::get('log');
        $this->_config = Zend_Registry::get('config')->import->content;
    }

    /**
     * Get language IDs for import of base content
     * @return array 
     */
    protected function _getLangugeIds()
    {
        $result = array();
        $languageModel = new Admin_Model_Language();
        $shortCodes = explode(',', $this->_config->languages);

        // Get language ID for language codes
        foreach ($shortCodes as $shortCode) {
            $languageId = $languageModel->findIdByShortCode($shortCode);

            // Check language ID
            if ($languageId) {
                array_push($result, $languageId);
            }
        }
        return $result;
    }

    /**
     * Get language short codes for import of products
     * @return array
     */
    protected function _getLangugeShortCodes()
    {
        $result = array();
        $languageModel = new Admin_Model_Language();
        $shortCodes = explode(',', $this->_config->languages);
        $destPrefix = $this->_config->downloadPath;

        // Get language ID for language codes
        foreach ($shortCodes as $shortCode) {
            $languageId = $languageModel->findIdByShortCode($shortCode);

            // Check language ID
            if ($languageId) {
                $result[$languageId] = $shortCode;

                // Check content path for language
                if (!file_exists($destPrefix . '/' . $shortCode)) {
                    mkdir($destPrefix . '/' . $shortCode);
                }
            }
        }
        return $result;
    }

    /**
     * Import base content
     */
    public function importBaseContent()
    {
        $startTime = microtime(true);
        $this->_logger->info(__METHOD__ . " started");
        $urlPrefix = $this->_config->protocol . '://' .
                $this->_config->login . ':' .
                $this->_config->password . '@' .
                $this->_config->server .
                $this->_config->referencesPath;
        $destPrefix = $this->_config->downloadPath;

        $this->_logger->debug(__METHOD__ . " started download of XML for languages");
        $destPath = $destPrefix . $this->_config->languagesList;
        $url = $urlPrefix . $this->_config->languagesList;
        // try to download XML for languages 
        if ($this->_downloader->downloadAndUnpackGzFile($url, $destPath)) {
            $this->_logger->debug(__METHOD__ . " started processing of XML for languages");
            $obj = new Menashop_Content_Languages($this->_config->languages); // a class to assist with parsing 
            $filePath = preg_replace('/\.gz$/', '', $destPath);
            $parser = new Menashop_XML_Parser($obj, $filePath);
            $parser->parseXML();
            $this->_logger->debug(__METHOD__ . ' ' . $obj->getReport());
            unlink($filePath);
        }

        $languageIds = $this->_getLangugeIds();
        if ($languageIds) {
            $this->_logger->debug(__METHOD__ . " started download of XML for manufacturers");
            $destPath = $destPrefix . $this->_config->manufacturersList;
            $url = $urlPrefix . $this->_config->manufacturersList;
            // try to download XML for manufacutrers 
            if ($this->_downloader->downloadAndUnpackGzFile($url, $destPath)) {
                $this->_logger->debug(__METHOD__ . " started processing of XML for manufacturers");
                $obj = new Menashop_Content_Manufacturers(); // a class to assist with parsing 
                $filePath = preg_replace('/\.gz$/', '', $destPath);
                $parser = new Menashop_XML_Parser($obj, $filePath);
                $parser->parseXML();
                $this->_logger->debug(__METHOD__ . ' ' . $obj->getReport());
                unlink($filePath);
            }

            $this->_logger->debug(__METHOD__ . " started download of XML for measures");
            $destPath = $destPrefix . $this->_config->measuresList;
            $url = $urlPrefix . $this->_config->measuresList;
            // try to download XML for measures 
            if ($this->_downloader->downloadAndUnpackGzFile($url, $destPath)) {
                $this->_logger->debug(__METHOD__ . " started processing of XML for measures");
                $obj = new Menashop_Content_Measures($languageIds); // a class to assist with parsing 
                $filePath = preg_replace('/\.gz$/', '', $destPath);
                $parser = new Menashop_XML_Parser($obj, $filePath);
                $parser->parseXML();
                $this->_logger->debug(__METHOD__ . ' ' . $obj->getReport());
                unlink($filePath);
            }

            $this->_logger->debug(__METHOD__ . " started download of XML for features");
            $destPath = $destPrefix . $this->_config->featuresList;
            $url = $urlPrefix . $this->_config->featuresList;
            // try to download XML for features 
            if ($this->_downloader->downloadAndUnpackGzFile($url, $destPath)) {
                $this->_logger->debug(__METHOD__ . " started processing of XML for features");
                $obj = new Menashop_Content_Features($languageIds); // a class to assist with parsing 
                $filePath = preg_replace('/\.gz$/', '', $destPath);
                $parser = new Menashop_XML_Parser($obj, $filePath);
                $parser->parseXML();
                $this->_logger->debug(__METHOD__ . ' ' . $obj->getReport());
                unlink($filePath);
            }

            $this->_logger->debug(__METHOD__ . " started download of XML for categories");
            $destPath = $destPrefix . $this->_config->categoriesList;
            $url = $urlPrefix . $this->_config->categoriesList;
            // try to download XML for categories 
            if ($this->_downloader->downloadAndUnpackGzFile($url, $destPath)) {
                $this->_logger->debug(__METHOD__ . " started processing of XML for categories");
                $obj = new Menashop_Content_Categories($languageIds, $this->_config, $this->_downloader); // a class to assist with parsing 
                $filePath = preg_replace('/\.gz$/', '', $destPath);
                $parser = new Menashop_XML_Parser($obj, $filePath);
                $parser->parseXML();
                $this->_logger->debug($obj->getReport());
                $this->_logger->debug(__METHOD__ . " started processing of XML for parent categories");
                $obj = new Menashop_Content_ParentCategories(); // a class to assist with parsing 
                $parser = new Menashop_XML_Parser($obj, $filePath);
                $parser->parseXML();
                $this->_logger->debug(__METHOD__ . ' ' . $obj->getReport());
                unlink($filePath);
            }

            $this->_logger->debug(__METHOD__ . " started download of XML for category features");
            $destPath = $destPrefix . $this->_config->categoryFeaturesList;
            $url = $urlPrefix . $this->_config->categoryFeaturesList;
            // try to download XML for category features
            if ($this->_downloader->downloadAndUnpackGzFile($url, $destPath)) {
                $this->_logger->debug(__METHOD__ . " started processing of XML for category features");
                $obj = new Menashop_Content_CategoryFeatures($languageIds); // a class to assist with parsing 
                $filePath = preg_replace('/\.gz$/', '', $destPath);
                $parser = new Menashop_XML_Parser($obj, $filePath);
                $parser->parseXML();
                $this->_logger->debug(__METHOD__ . ' ' . $obj->getReport());
                unlink($filePath);
            }
        }
        $totalTime = round(microtime(true) - $startTime, 1);
        $this->_logger->info(__METHOD__ . " spent $totalTime s");
    }

    /**
     * Import product list
     */
    public function importProductList()
    {
        $startTime = microtime(true);
        $this->_logger->info(__METHOD__ . " started");
        $this->_logger->debug(__METHOD__ . " started download of CSV with list of products");

        // Parameters for download
        $url = $this->_config->protocol . '://' .
                $this->_config->login . ':' .
                $this->_config->password . '@' .
                $this->_config->server .
                $this->_config->productsPath .
                $this->_config->productsList;
        $destPath = $this->_config->downloadPath . $this->_config->productsList;

        // Check download status
        if ($this->_downloader->downloadAndUnpackGzFile($url, $destPath)) {
            $this->_logger->debug(__METHOD__ . " started processing of CSV with list of products");

            // Read product list from file
            $filePath = preg_replace('/\.gz$/', '', $destPath);
            $providerProductModel = new Admin_Model_ProviderProduct();
            $providerProductModel->loadAllFromFile($filePath);
            unlink($filePath);
        }
        $totalTime = round(microtime(true) - $startTime, 1);
        $this->_logger->info(__METHOD__ . " spent $totalTime s");
    }

    /**
     * Import products
     */
    public function importProducts()
    {
        $startTime = microtime(true);
        $this->_logger->info(__METHOD__ . " started");
        $languageShortCodes = $this->_getLangugeShortCodes();
        if ($languageShortCodes) {
            $urlPrefix = $this->_config->protocol . '://' .
                    $this->_config->login . ':' .
                    $this->_config->password . '@' .
                    $this->_config->server .
                    $this->_config->productsPath;
            $destPrefix = $this->_config->downloadPath;

            // Get list of products for import
            $providerProductModel = new Admin_Model_ProviderProduct();
            $products = $providerProductModel->getAllForImport();
            $this->_logger->info(__METHOD__ . " count of products for import = " . count($products));
            $totalImportedProducts = 0;

            //$this->_products = array();
            //array_push($this->_products, 1004432);
            // Import all product from list
            foreach ($products as $contentProductId) {

                // Import product for cessary languages
                foreach ($languageShortCodes as $languageId => $shortCode) {
                    $this->_logger->debug(__METHOD__ . " started import of product with ID = $contentProductId for $shortCode language ");
                    $destPath = $destPrefix . $shortCode . '/' . $contentProductId . '.xml.gz';
                    $url = $urlPrefix . $shortCode . '/' . $contentProductId . '.xml.gz';

                    // Try to download product XML
                    if ($this->_downloader->downloadAndUnpackGzFile($url, $destPath)) {

                        // Parse product XML
                        $obj = new Menashop_Content_Product($contentProductId, $languageId, $this->_config, $this->_downloader);
                        $filePath = preg_replace('/\.gz$/', '', $destPath);
                        $parser = new Menashop_XML_Parser($obj, $filePath);
                        if ($parser->parseXML()) {
                            $totalImportedProducts++;
                        }
                        $this->_logger->debug(__METHOD__ . ' ' . $obj->getReport());
                        unlink($filePath);
                    }
                }
            }
            $this->_logger->debug(__METHOD__ . " count of imported products = " . $totalImportedProducts / count($languageShortCodes));
        }
        $totalTime = round(microtime(true) - $startTime, 1);
        $this->_logger->info(__METHOD__ . " spent $totalTime s");
    }

}
